﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.QPZS.EPC.API.Domain.Entities;
using Wicture.QPZS.EPC.API.InvokeContextBuilders;
using Wicture.QPZS.EPC.API.Throtteds;
using Wicture.QPZS.EPC.API.Throttlings;

namespace Wicture.QPZS.EPC.API.Domain
{
    public class ThrottlingControllerNew : IThrottlingController
    {
        private readonly IThrottlingContextBuilderProxy _throttlingContextBuilderProxy;
        private readonly IThrottedProxy _throttedProxy;
        private readonly IThrottingProxy _throttingProxy;

        public ThrottlingControllerNew(IThrottlingContextBuilderProxy throttlingContextBuilderProxy, IThrottedProxy throttedProxy, IThrottingProxy throttingProxy)
        {
            _throttlingContextBuilderProxy = throttlingContextBuilderProxy;
            _throttedProxy = throttedProxy;
            _throttingProxy = throttingProxy;
        }

        public void Init()
        {
            ApiInvocationHandler.Invoking += ApiInvocationHandler_Invoking;
            ApiInvocationHandler.Invoked += ApiInvocationHandler_Invoked;
        }

        private void ApiInvocationHandler_Invoking(object sender, ApiInvokingArgs e)
        {
            if (IgnoreThrottling(e.Context.HttpContext))
            {
                return;
            }
            var context = _throttlingContextBuilderProxy.Build(sender, e);
            _throttingProxy.Throtting(context);
            e.Context.HttpContext.Items.Add("ThrottlingContext", context);
        }

        private void ApiInvocationHandler_Invoked(object sender, ApiInvokedArgs e)
        {
            if (IgnoreThrottling(e.Context.HttpContext))
            {
                return;
            }
            var context = e.Context.HttpContext.Items["ThrottlingContext"] as ThrottlingContext;
            _throttlingContextBuilderProxy.Build(context, sender, e);
            _throttedProxy.Throtted(context);
        }

        private bool IgnoreThrottling(HttpContext context)
        {
            return context.Request.Path.Value.Contains("api/admins");
        }
    }
}
